package io.renren.modules.weixin.Service;

import io.renren.modules.weixin.Util.MessageUtil;
import io.renren.modules.weixin.entity.StatisticsEntity;
import io.renren.modules.weixin.entity.WxBindEntity;
import io.renren.modules.weixin.message.resp.Article;
import io.renren.modules.weixin.message.resp.NewsMessage;
import io.renren.modules.weixin.message.resp.TextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("CoreService")
public class CoreService {
    @Value("${static.url}")
    private String staticUrl;
    @Autowired
    private WxBindService wxBindService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private ZbAdminService zbAdminService;

    public String processRequest(HttpServletRequest request) {
        String respMessage = null;
        try {
            // 默认返回的文本消息内容
            String respContent = "请求处理异常，请稍候尝试！";

            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);

            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            //消息内容
            String content = requestMap.get("Content");
            // 消息类型
            String msgType = requestMap.get("MsgType");


            // 回复文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
            textMessage.setFuncFlag(0);

            // 创建图文消息
            NewsMessage newsMessage = new NewsMessage();
            newsMessage.setToUserName(fromUserName);
            newsMessage.setFromUserName(toUserName);
            newsMessage.setCreateTime(new Date().getTime());
            newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
            newsMessage.setFuncFlag(0);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                respContent = "您发送的是文本消息！";
                WxBindEntity isHasFormId = wxBindService.selectByFormName(fromUserName);
                if((null != isHasFormId) && (0 == isHasFormId.getAdminName().compareTo("1111"))){
                    WxBindEntity wx = new WxBindEntity();
                    wx.setAdminName(content);
                    wx.setFromName(fromUserName);
                    wxBindService.updataByFormName(content,fromUserName);
                    respContent = "绑定数据成功！";
                }
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                respContent = "您发送的是图片消息！";
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
            // 地理位置消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
                respContent = "您发送的是地理位置消息！";
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
            // 链接消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
                respContent = "您发送的是链接消息！";
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
            // 音频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
                respContent = "您发送的是音频消息！";
                textMessage.setContent(respContent);
                respMessage = MessageUtil.textMessageToXml(textMessage);
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    respContent = "谢谢您的关注！";
                    textMessage.setContent(respContent);
                    respMessage = MessageUtil.textMessageToXml(textMessage);
                }
                // 取消订阅
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                }
                // 自定义菜单点击事件
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    // 事件KEY值，与创建自定义菜单时指定的KEY值对应
                    String eventKey = requestMap.get("EventKey");

                    if (eventKey.equals("11")) {
                        respContent = "绑定数据源被点击！";
                        WxBindEntity isHasFormId = wxBindService.selectByFormName(fromUserName);
                        if(isHasFormId == null){
                            WxBindEntity wx = new WxBindEntity();
                            wx.setAdminName("1111");
                            wx.setFromName(fromUserName);
                            wxBindService.insert(wx);
                            respContent = "请输入数据源";
                        }else if(0 == isHasFormId.getAdminName().compareTo("1111")){
                            respContent = "请输入数据源";
                        }else {
                            respContent = "你已成功绑定 "+isHasFormId.getAdminName();
                        }
                        textMessage.setContent(respContent);
                        respMessage = MessageUtil.textMessageToXml(textMessage);
                    } else if (eventKey.equals("12")) {
                        respContent = "打开自动预警！";
                        WxBindEntity wbind = wxBindService.selectByFormName(fromUserName);
                        String user = wbind.getAdminName();
                        zbAdminService.updateStatusOn(user);
                        textMessage.setContent(respContent);
                        respMessage = MessageUtil.textMessageToXml(textMessage);
                    } else if (eventKey.equals("13")) {
                        respContent = "关闭自动预警！";
                        WxBindEntity wbind = wxBindService.selectByFormName(fromUserName);
                        String user = wbind.getAdminName();
                        zbAdminService.updateStatusOff(user);
                        textMessage.setContent(respContent);
                        respMessage = MessageUtil.textMessageToXml(textMessage);
                    } else if (eventKey.equals("21")) {
                        WxBindEntity wbind = wxBindService.selectByFormName(fromUserName);
                        String user = wbind.getAdminName();
                        StatisticsEntity se = zbAdminService.statisticsAdmin(user);
                        List<Article> articleList = new ArrayList<Article>();
                        Article article = new Article();
                        article.setTitle("监控信息");
                        article.setDescription("监控指标："+se.getCountValue()+"条：通过"+se.getOkValue()+"条、蓝色告警"+se.getWarningValue()+"条、橙色告警"+se.getAlertValue()+"条、红色告警"+se.getErrorValue()+"条。");
                        article.setPicUrl(staticUrl+"/wechat/phone/images/zbjt.jpg");
                        article.setUrl(staticUrl+"/wechat/phone/home.html?creator="+user);
                        articleList.add(article);
                        // 设置图文消息个数
                        newsMessage.setArticleCount(articleList.size());
                        // 设置图文消息包含的图文集合
                        newsMessage.setArticles(articleList);
                        // 将图文消息对象转换成xml字符串
                        respMessage = MessageUtil.newsMessageToXml(newsMessage);
                    } else if (eventKey.equals("31")) {
                        int flag = weixinService.quickSelect(fromUserName);
                        if(flag == 1){
                            respContent = "您未配置或未开启监控指标";
                        }else{
                            respContent = "";
                        }
                        textMessage.setContent(respContent);
                        respMessage = MessageUtil.textMessageToXml(textMessage);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return respMessage;
    }
}
